package com.mcode.blog.utils;

import com.alibaba.fastjson.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class QiniuUtils {

    public static String url;

    //修改以下两个值放到proprietarties中，在密钥管理中获取
    @Value("${qiniu.kodo.accessKey}")
    private String accessKey;

    @Value("${qiniu.kodo.accessSecretKey}")
    private String accessSecretKey;

    @Value("${qiniu.kodo.bucket}")
    private String bucket;


    @Value("${qiniu.kodo.domain}")
    public void setUrl(String url) {
        QiniuUtils.url = url;
    }


    /**
     * 上传图片
     *
     * @param file
     * @param fileName
     * @return
     */
    public String upload(MultipartFile file, String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传，修改上传名称为自己创立空间的空间名称（是你自己的）
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);

            String uploadPath = imageUploadPath() + fileName;
            Response response = uploadManager.put(uploadBytes, uploadPath, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);

            // 返回地址
            return QiniuUtils.url + uploadPath;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    /**
     * 图片上传文件路径
     *
     * @return
     */
    public String imageUploadPath() {
        // 时间命名的文件夹
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dirName = formatter.format(new Date());
        return "image/" + dirName + '/';
    }
}

